import json

import requests
from virus_mysql_helper import *

db_con = get_connection()
db_cursor = get_cursor(db_con)


# 爬取疫情数据
def get_page():
    url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5'
    headers = {
        'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Mobile Safari/537.36'
    }
    r = requests.get(url, headers)
    res = json.loads(r.text)
    data_res = json.loads(res['data'])
    return data_res


def main():
    json_data = get_page()
    record_data = json_data['lastUpdateTime'][:10]


    # 获取最新的当天数据
    # 数据更新时间
    last_updata_time = json_data['lastUpdateTime']
    print(last_updata_time)

    china_total = json_data['chinaTotal']
    china_add = json_data['chinaAdd']
    # 首先查询有没有当前更新时间的数据
    result = get_day_data(db_con, db_cursor,last_updata_time)
    if len(result)>0:
        # 已经有最新数据
        pass
    else:
        # 没有最新数据，把当天的数据删除，插入最新数据
        delete_day_data(db_con, db_cursor,record_data)
        insert_today_data(db_con, db_cursor, record_data,last_updata_time,china_total,china_add)


    # 获取疫情历史数据 to:把今天的数据也放进去
    # day_list = json_data['chinaDayList']
    # for day_total in day_list:
    #     # 保存数据库 do:有数据就更新，没有数据就新增
    #     save_day_data(db_con, db_cursor, day_total)
    #     day_list = json_data['chinaDayAddList']
    # 获取新增数据
    # for day_add in day_list:
    #     update_day_data(db_con, db_cursor, day_add)


    # 获取各省的数据
    # 首先查询有没有当前更新时间的数据
    result = get_provincee_day_data(db_con, db_cursor, last_updata_time)
    if len(result) > 0:
        pass
    else:
        # 没有最新数据，把当天的数据删除，插入最新数据
        delete_province_data(db_con, db_cursor, record_data)

        province_list = json_data['areaTree'][0]['children']
        for province_data in province_list:
            save_province_data(db_con, db_cursor, record_data, province_data,last_updata_time)


if __name__ == '__main__':
    main()
